%%%-------------------------------------------------------------------
%%% @author wukai
%%% @copyright (C) 2017, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 23. 十月 2017 19:59
%%%-------------------------------------------------------------------
-module(protocol_util).
-include("../include/mqtt_protocol.hrl").
-author("wukai").

-export([len_bytes/1]).
-export([bytes_len/1]).
-export([send_data/3]).

len_bytes(Value) ->
  len_bytes(Value, <<>>).
%%计算剩余长度
len_bytes(Value, Bin) when Value > 0 ->
  Rem = Value rem 128, %%取余数% 65
  DIV = Value div 128, %%除以128 判断后面是否还有数据
  if
    DIV > 0 ->
      Rem1 = Rem bor 128,
      %%io:format("~B",[Rem1]),
      len_bytes(DIV, <<Bin/binary, Rem1:8>>);
    true ->
      %%io:format("~B",[Rem]),
      <<Bin/binary, Rem:8>>
  end;

len_bytes(Value, Encode) when Value == 0 -> Encode.


bytes_len(List) ->
  bytes_len(List, 0, 1).

%%从字节列表中获取剩余长度的值
bytes_len([H | T], Value, Index) ->
  Value1 = len_multi(H, Index) + Value,
  NIndex = Index + 1,
  bytes_len(T, Value1, NIndex);

bytes_len([], Value, _) -> Value.

len_multi(Byte, 1) ->
  Byte band 127;
len_multi(Byte, 2) ->
  (Byte band 127) * 128;
len_multi(Byte, 3) ->
  (Byte band 127) * 128 * 128;
len_multi(Byte, 4) ->
  (Byte band 127) * 128 * 128 * 128.


send_data(_, State, Bin) ->
  T = State#state.trans,
  S = State#state.socket,
  T:send(S, Bin).

